{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "a20a2420",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "原多项式: x**3 - 10*x**2 + 31*x - 30\n",
      "质因式分解: (x - 5)*(x - 3)*(x - 2)\n"
     ]
    }
   ],
   "source": [
    "# 质因式分解\n",
    "from sympy import symbols, factor\n",
    "from sympy.abc import x\n",
    "\n",
    "polynomial = x**3 -10*x**2 + 31*x - 30\n",
    "\n",
    "factored_polynomial = factor(polynomial)\n",
    "\n",
    "print(\"原多项式:\", polynomial)\n",
    "print(\"质因式分解:\", factored_polynomial)\n",
    "\n",
    "# 输出\n",
    "# 原多项式: x**3 - 10*x**2 + 31*x - 30\n",
    "# 质因式分解: (x - 5)*(x - 3)*(x - 2)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "89ff714b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "拉格朗日多项式: (x - 3)*(x - 2) - 3*(x - 3)*(x - 1) + 4*(x - 2)*(x - 1)\n",
      "化简后的多项式: 2*x**2 - 5*x + 5\n",
      "在 x=4 的值: 8\n"
     ]
    }
   ],
   "source": [
    "# 拉格朗日插值\n",
    "from sympy import symbols\n",
    "from sympy.abc import x\n",
    "from sympy.polys.polyfuncs import interpolating_poly\n",
    "\n",
    "# 给定的插值点和相应的函数值\n",
    "data = [(1, 2), (2, 3), (3, 8)]\n",
    "\n",
    "if isinstance(data, dict):\n",
    "    X, Y = list(zip(*data.items()))\n",
    "else:\n",
    "    if isinstance(data[0], tuple):\n",
    "        X, Y = list(zip(*data))\n",
    "    else:\n",
    "        X = list(range(1, n + 1))\n",
    "        Y = list(data)\n",
    "\n",
    "# 使用 lagrange 函数构造拉格朗日插值多项式\n",
    "interpolation_polynomial = interpolating_poly(len(data), x, X, Y)\n",
    "\n",
    "# 输出插值多项式\n",
    "print(\"拉格朗日多项式:\", interpolation_polynomial)\n",
    "print(\"化简后的多项式:\", interpolation_polynomial.expand())\n",
    "# 通过插值多项式计算 x=4 的值\n",
    "result = interpolation_polynomial.subs(x, 3)\n",
    "print(\"在 x=4 的值:\", result)\n",
    "\n",
    "# 示例输出\n",
    "# 拉格朗日多项式: (x - 3)*(x - 2) - 3*(x - 3)*(x - 1) + 4*(x - 2)*(x - 1)\n",
    "# 化简后的多项式: 2*x**2 - 5*x + 5\n",
    "# 在 x=4 的值: 8\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6f1b05a6",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
